<!-- 报告记录页 -->
<template>
  <div class="skin-records-container">
    <vab-query-form>
      <!-- <vab-query-form-right-panel> -->
      <el-form ref="form" :inline="true" :model="queryForm" :rules="rules" @submit.native.prevent>
        <el-form-item label="手机号" prop="mobile">
          <el-input
            v-model="queryForm.mobile"
            placeholder="手机号"
            οninput="value=value.replace(/[^\d]/g,'');if(value.length > 11)value = value.slice(0, 11)"
          />
        </el-form-item>

        <el-form-item label="报告时间" width="180px">
          <el-date-picker
            v-model="firstClockTimes"
            end-placeholder="结束时间"
            format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始时间"
            type="datetimerange"
            @change="handleQuery"
          />
        </el-form-item>
        <el-form-item label="综合得分">
          <el-col :span="10">
            <el-input v-model="queryForm.totalScoreMin" placeholder="开始综合得分" type="number" />
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="10">
            <el-input v-model="queryForm.totalScoreMax" placeholder="结束综合得分" type="number" />
          </el-col>
        </el-form-item>
        <el-form-item label="top选项" prop="tops">
          <el-select v-model="topsValues" filterable multiple placeholder="请选择">
            <el-option
              v-for="item in optionsTops"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" native-type="submit" type="primary" @click="handleQuery">
            查询
          </el-button>

          <el-button icon="el-icon-download" native-type="submit" type="primary" @click="exportAll">
            导出
          </el-button>
        </el-form-item>
      </el-form>
      <!-- </vab-query-form-right-panel> -->
    </vab-query-form>

    <el-table
      ref="tableSort"
      v-loading="listLoading"
      :data="list"
      :element-loading-text="elementLoadingText"
      :height="height"
      @sort-change="tableSortChange"
    >
      <template v-for="item in thHeaders">
        <el-table-column
          v-if="item.prop === 'mobile'"
          :key="item.prop"
          :label="item.label"
          :prop="item.prop"
          show-overflow-tooltip
          :width="item.width"
        >
          <template slot-scope="scope">
            <router-link :to="{ name: 'userList', query: { mobile: scope.row.mobile } }">
              <span>
                {{ scope.row.mobile }}
              </span>
            </router-link>
          </template>
        </el-table-column>
        <el-table-column
          v-else-if="item.prop === 'detectionTime'"
          :key="item.prop"
          align="center"
          :formatter="showTime"
          :label="item.label"
          :prop="item.prop"
          show-overflow-tooltip
          :width="item.width"
        />

        <el-table-column
          v-else
          :key="item.prop"
          :label="item.label"
          :prop="item.prop"
          show-overflow-tooltip
          :width="item.width"
        />
      </template>
    </el-table>
    <el-pagination
      :background="background"
      :current-page="queryForm.page"
      :layout="layout"
      :page-size="queryForm.size"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
  </div>
</template>

<script>
  import dayjs from 'dayjs'
  import { getStatisticsProposalsList, exportStatisticsUrlList } from '@/api/configration'

  export default {
    name: 'ProposalsListTable',

    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'gray',
          deleted: 'danger',
        }
        return statusMap[status]
      },
    },
    data() {
      return {
        imgShow: true,
        list: [],
        imageList: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        background: true,
        selectRows: '',
        elementLoadingText: '正在加载...',
        firstClockTimes: [],
        queryForm: {
          page: 1,
          size: 20,
          mobile: '',
        },
        thHeaders: [
          { prop: 'openid', label: '用户openid', width: '120' },
          { prop: 'mobile', label: '用户手机号', width: '120' },
          { prop: 'nickName', label: '用户昵称', width: '100' },
          { prop: 'detectionTime', label: '报告时间', width: '150' },
          { prop: 'total', label: '综合得分', width: '100' },
          { prop: 'skinCondition', label: '测肤得分', width: '100' },
          { prop: 'foodHabit', label: '饮食得分', width: '100' },
          { prop: 'skinHabit', label: '护肤得分', width: '100' },
          { prop: 'lifeHabit', label: '生活得分', width: '100' },
          { prop: 'emotion', label: '情绪得分', width: '100' },
          { prop: 'tops', label: 'top关键问题', width: '100' },
          { prop: 'tags', label: '标签', width: '180' },
          // '光泽感',
          // '水润度',
        ],
        rules: {
          mobile: [{ min: 11, message: '手机号格式不正确', trigger: 'blur' }],
          totalScoreMin: [{ type: 'number', trigger: 'blur', message: '综合得分是数字' }],
          totalScoreMax: [{ type: 'number', trigger: 'blur', message: '综合得分是数字' }],
        },
        topsValues: [],
        optionsTops: [
          {
            value: '痘痘问题',
            label: '痘痘问题',
          },
          {
            value: '肌肤偏油',
            label: '肌肤偏油',
          },
          {
            value: '毛孔问题',
            label: '毛孔问题',
          },
          {
            value: '黑头问题',
            label: '黑头问题',
          },
          {
            value: '肌肤稳定性较低',
            label: '肌肤稳定性较低',
          },
          {
            value: '水润度较低',
            label: '水润度较低',
          },
          {
            value: '光泽感较弱',
            label: '光泽感较弱',
          },
          {
            value: '嗜辛辣油腻',
            label: '嗜辛辣油腻',
          },
          {
            value: '缺乏锻炼',
            label: '缺乏锻炼',
          },
          {
            value: '奶制品摄入量过高',
            label: '奶制品摄入量过高',
          },
          {
            value: '嗜甜食碳水',
            label: '嗜甜食碳水',
          },
          {
            value: '过度清洁',
            label: '过度清洁',
          },
          {
            value: '情绪不稳定',
            label: '情绪不稳定',
          },
          {
            value: '压力大',
            label: '压力大',
          },
          {
            value: '肤质脆弱',
            label: '肤质脆弱',
          },
          {
            value: '护肤意识弱',
            label: '护肤意识弱',
          },
          {
            value: '无防晒意识',
            label: '无防晒意识',
          },
          {
            value: '睡眠过少',
            label: '睡眠过少',
          },
          {
            value: '忽视营养补充',
            label: '忽视营养补充',
          },
          {
            value: '运动时间短',
            label: '运动时间短',
          },
          {
            value: '情绪调节能力弱',
            label: '情绪调节能力弱',
          },
          {
            value: '易容貌焦虑',
            label: '易容貌焦虑',
          },
          {
            value: '轻度痘痘问题',
            label: '轻度痘痘问题',
          },
          {
            value: '肌肤偏干',
            label: '肌肤偏干',
          },
          {
            value: '轻微毛孔问题',
            label: '轻微毛孔问题',
          },
          {
            value: '轻度黑头问题',
            label: '轻度黑头问题',
          },
          {
            value: '肌肤稳定性一般',
            label: '肌肤稳定性一般',
          },
          {
            value: '水润度偏低',
            label: '水润度偏低',
          },
          {
            value: '光泽感待加强',
            label: '光泽感待加强',
          },
        ],
      }
    },
    computed: {
      height() {
        return this.$baseTableHeight()
      },
    },
    created() {
      // this.fetchData()
    },
    beforeDestroy() {
      if (this.loadingInstance) this.loadingInstance.close()
    },
    mounted() {
      this.queryForm = { ...this.queryForm, ...this.$route.query }
      this.fetchData()
    },
    methods: {
      showTime(row, column, cellValue, index) {
        console.log('dayjs', dayjs(cellValue).format('yyyy-MM-dd HH:mm:ss'))
        // console.log(column)
        console.log(cellValue === null)
        console.log('cellValue', cellValue === null)
        // console.log(index)

        if (cellValue) {
          return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
        }
      },
      showIsClock(row, column, cellValue, index) {
        console.log(row)
        console.log(column)
        console.log(cellValue)
        console.log(index)

        return cellValue ? '是' : '否'
      },

      tableSortChange() {
        const imageList = []
        this.$refs.tableSort.tableData.forEach((item, index) => {
          imageList.push(item.img)
        })
        this.imageList = imageList
      },

      handleSizeChange(val) {
        this.queryForm.size = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.page = val
        this.fetchData()
      },
      handleQuery() {
        this.queryForm.page = 1
        if (
          this.firstClockTimes &&
          Array.isArray(this.firstClockTimes) &&
          this.firstClockTimes.length > 1
        ) {
          this.queryForm.start = dayjs(this.firstClockTimes[0]).valueOf()
          this.queryForm.end = dayjs(this.firstClockTimes[1]).valueOf()
        } else {
          delete this.queryForm.start
          delete this.queryForm.end
        }
        if (this.topsValues && Array.isArray(this.topsValues)) {
          this.queryForm.tops = this.topsValues.join(',')
        } else {
          delete this.queryForm.tops
        }
        console.log('handleQuery', this.queryForm)
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        // this.queryForm
        try {
          const { data } = await getStatisticsProposalsList(this.queryForm)
          console.log('fetchData 测肤记录获取的数据', data)
          if (data && typeof data === 'object') {
            const { count, rows } = data
            if (rows && Array.isArray(rows)) {
              this.list = rows
              const imageList = []
              rows.forEach((item, index) => {
                imageList.push(item.img)
              })
              this.imageList = imageList
              this.total = count || 0
              setTimeout(() => {
                this.listLoading = false
              }, 500)
            }
          }
        } catch (error) {
          this.$baseMessage('获取的数据失败', 'error')
          console.log('测肤记录获取的数据失败', error)
        }
      },
      //全部数据导出
      async exportAll() {
        let obj = { ...this.queryForm }
        delete obj.page
        delete obj.size
        console.log('..obj....', obj)
        let loadingInstance = (this.loadingInstance = this.$loading({
          fullscreen: true,
          text: '请求数据中',
          background: 'rgba(0, 0, 0, 0.5)',
        }))

        const { data } = await exportStatisticsUrlList('proposals', obj).catch(() => {
          loadingInstance.close()
        })
        console.log('..exportAll....', data)
        if (data && typeof data === 'object') {
          let { url } = data
          if (typeof url === 'string') {
            // let a_link = document.createElement('a')
            // 这里是将url转成blob地址，
            fetch(url)
              .then((response) => {
                // return new Blob([response])
                return response.blob()
              })
              .then((blob) => {
                // 将链接地址字符内容转变成blob地址
                let url = window.URL.createObjectURL(blob)
                console.log('url', url)
                let a = document.createElement('a')
                a.href = url
                let time = dayjs().format('YYYY-MM-DD')
                a.download = `${time}报告记录导出.xlsx`
                document.body.appendChild(a) // we need to append the element to the dom -> otherwise it will not work in firefox
                a.click()
                loadingInstance.close()
                a.remove() //afterwards we remove the element again
              })
              .catch((err) => {
                loadingInstance.close()
                this.$baseMessage('测肤记录获取的数据失败', 'error')
                console.log('测肤记录获取的数据失败', err)
              })
          }
        } else {
          loadingInstance.close()
          this.$baseMessage('测肤记录获取的数据失败', 'error')
        }
      },
    },
  }
</script>
<style lang="scss" scope>
  .line {
    text-align: center;
  }
  .el-select {
    .el-select__tags {
      max-height: 50px;
      overflow: auto;
    }
  }
</style>
<style scope>
  /*表头换行*/
  .skin-records-container .el-table .cell {
    white-space: pre-line;
  }
  .skin-records-container .el-table th.el-table__cell > .cell {
    white-space: pre;
  }
</style>
